package com.winit.schedule.job.tracker.util;

import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.util.StringUtils;

import com.winit.schedule.core.conf.Configuration;
import com.winit.schedule.job.tracker.conf.JobConfiguration;

/**
 * 邮件发送
 * 
 * @author jianke.zhang 2015-4-16 下午5:44:14
 * @since 1.0
 */
public class MailHelper {

	private JavaMailSender mailSender;

	private Configuration conf;

	public MailHelper(JavaMailSender mailSender, Configuration conf) {
		this.mailSender = mailSender;
		this.conf = conf;
	}

	/**
	 * 发送邮件给默认接收人
	 * 
	 * @param subject
	 * @param content
	 */
	public void sendTextMail(String subject, String content) {
		String to = conf.get(JobConfiguration.ALARM_MAIL_TO);
		sendTextMail(to, subject, content);
	}

	/**
	 * 邮件发送
	 * 
	 * @param from
	 * @param to
	 * @param subject
	 * @param content
	 */
	public void sendTextMail(String to, String subject, String content) {
		String from = conf.get(JobConfiguration.ALARM_MAIL_FROM);

		// 找不到收件人，则获取默认邮件接收人
		if (StringUtils.isEmpty(to)) {
			to = conf.get(JobConfiguration.ALARM_MAIL_TO);
		}
		
		if (StringUtils.isEmpty(to)) {
			return; // 找不到邮件接收人，直接退出
		}
		String[] mailTo = StringUtils
				.tokenizeToStringArray(to, ",", true, true);
		sendTextMail(from, mailTo, subject, content);
	}

	/**
	 * 邮件发送
	 * 
	 * @param from
	 * @param to
	 * @param subject
	 * @param content
	 */
	public void sendTextMail(String from, String[] to, String subject,
			String content) {
		boolean mailEnable = conf
				.getBoolean(JobConfiguration.MAIL_ENABLE, true);
		if (mailEnable) {
			SimpleMailMessage mailMessage = new SimpleMailMessage();
			mailMessage.setFrom(from);
			mailMessage.setTo(to);
			mailMessage.setSubject(subject);
			mailMessage.setText(content.toString());
			mailSender.send(mailMessage);
		}
	}
}
